/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;

import com.phonebooksharing.android.activities.dashboard.PostcardReaderActivity;
import com.phonebooksharing.android.util.GalleryUtilities;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.IOUtilities;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.android.widgets.drawable.FastBitmapDrawable;
import com.phonebooksharing.dto.dashboard.DashboardReaderItem;
import com.phonebooksharing.dto.friend.ContactItem;
import com.phonebooksharing.dto.gallery.PostCardItem;

@SuppressWarnings("unchecked")
public class DownloadNetworkPostcardImageTask extends NetworkHandlerTask<Object, Object, DashboardReaderItem<ContactItem>> {
    private Activity caller;
    private ProgressDialog d;
    private File front, back;
//    private DashboardReaderItem<ContactItem> dr;
    
    public DownloadNetworkPostcardImageTask(Activity caller, DashboardReaderItem<ContactItem> dr) {
        this.caller = caller;
//        this.dr = dr;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        d = new ProgressDialog(caller);
        d.setTitle("Downloading Postcard");
        d.setMessage("Please wait while loading...");
        d.setIndeterminate(true);
        d.setCancelable(true);
        d.show();
    }

    @Override
    protected DashboardReaderItem<ContactItem> doInBackground(Object... params) {
        long id = (Long) params[0];
        int w = (Integer) params[1];
        int h = (Integer) params[2];

        try {
            // TODO: shall we add this to cache?!?!
            // ImageUtilities.addToCache(id, b);

            //Global.IMAGE_SERVLET_URL, "gic" /*ac*/, id /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, "" /*mt*/, w /*w*/, h /*h*/);
            
            String url = String.format("http:" + Global.IMAGE_SERVLET_URL, "gpcf" /*ac*/, id /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, "" /*mt*/, w /*w*/, h /*h*/);
            front = IOUtilities.getExternalFile(System.currentTimeMillis() + ".dat");
            IOUtilities.add2collection(front.getAbsolutePath());
            GalleryUtilities.downloadAndStore(url, front);

            
            url = String.format("http:" + Global.IMAGE_SERVLET_URL, "gpcb" /*ac*/, id /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, "" /*mt*/, w /*w*/, h /*h*/);
            back = IOUtilities.getExternalFile(System.currentTimeMillis() + ".dat");
            IOUtilities.add2collection(back.getAbsolutePath());
            GalleryUtilities.downloadAndStore(url, back);
            
            ContentResolver cr = caller.getContentResolver();
            Global.setPostcard(new FastBitmapDrawable(GalleryUtilities.getBitmapFromFile(cr, front)), 
                               new FastBitmapDrawable(GalleryUtilities.getBitmapFromFile(cr, back)));
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (DashboardReaderItem<ContactItem>) params[3];
    }

    @Override
    protected void onPostExecute(DashboardReaderItem<ContactItem> result) {
        super.onPostExecute(result);

        final DashboardReaderItem<ContactItem> dr = result;
        final PostCardItem f = (PostCardItem) dr.getItem();

        final Intent i = new Intent(caller, PostcardReaderActivity.class);
        i.putExtra(PostcardReaderActivity.PHOTO_TITLE,     f.title);
        i.putExtra(PostcardReaderActivity.PHOTO_LATITUDE,  f.postLatitude);
        i.putExtra(PostcardReaderActivity.PHOTO_LONGITUDE, f.postLongitude);

        // common stuff
        FastBitmapDrawable fb = GalleryUtilities.getFromContactCache(f.andID);
        if(fb != null) {
            i.putExtra(PostcardReaderActivity.FRIEND_ICON, fb.getBitmap());
        } else {
            i.putExtra(PostcardReaderActivity.FRIEND_ICON, GalleryUtilities.noPictureBitmap.getBitmap());
        }
        i.putExtra(PostcardReaderActivity.FRIEND_NAME,      f.name);
        i.putExtra(PostcardReaderActivity.FRIEND_STATUS,    f.status);
        i.putExtra(PostcardReaderActivity.FRIEND_LOCATION,  f.location);
        i.putExtra(PostcardReaderActivity.SENT_WHEN,        dr.getWhen());
        i.putExtra(PostcardReaderActivity.DASHBOARD_ID,     dr.getId());
        i.putExtra(PostcardReaderActivity.FRIEND_ID,        f.andID);
        i.putExtra(PostcardReaderActivity.DASHBOARD_READER_ITEM, dr);

        i.putExtra(PostcardReaderActivity.FRONT_FILENAME, front.getAbsolutePath());
        i.putExtra(PostcardReaderActivity.BACK_FILENAME,  back.getAbsolutePath());

        d.dismiss();
        caller.startActivity(i);
    }
}